package org.dtrd.modules.organization.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dtrd.common.util.StringUtil;
import org.dtrd.config.system.SystemState;
import org.dtrd.modules.dict.service.IDtrdEntRdDicDistrictService;
import org.dtrd.modules.food.entity.po.DtrdExtEmsYwCookbooks;
import org.dtrd.modules.organization.entity.bean.OrganizationDetail;
import org.dtrd.modules.organization.entity.bean.OrganizationListInfo;
import org.dtrd.modules.organization.entity.po.DtrdEntRdOrganization;
import org.dtrd.modules.organization.entity.request.OrganizationPageRequest;
import org.dtrd.modules.organization.mapper.DtrdEntRdOrganizationMapper;
import org.dtrd.modules.organization.service.IDtrdEntRdOrganizationService;
import org.dtrd.modules.service.entity.po.DtrdEntRdServicePackage;
import org.dtrd.modules.service.service.IDtrdEntRdServicePackageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static org.dtrd.common.api.vo.Result.error;


/**
 * <p>
 * 机构表 服务实现类
 * </p>
 *
 * @author QR
 * @since 2021-12-14
 */
@DS("multi-datasource1")
@Service
public class DtrdEntRdOrganizationServiceImpl extends ServiceImpl<DtrdEntRdOrganizationMapper, DtrdEntRdOrganization> implements IDtrdEntRdOrganizationService {

    @Autowired
    private IDtrdEntRdDicDistrictService districtInfoService;
    @Autowired
    private IDtrdEntRdServicePackageService packageService;

    @Override
    public List<OrganizationListInfo> getOrganizationList(Integer packageId) {
        DtrdEntRdServicePackage packageInfo = packageService.getById(packageId);
        String[] orgCodes = packageInfo.getOrgCode().split(",");
        LambdaQueryWrapper<DtrdEntRdOrganization> queryWrapper = baseQueryWrapper()
                .in(DtrdEntRdOrganization::getOrganizationCode, (Object[]) orgCodes);
        List<DtrdEntRdOrganization> poList = list(queryWrapper);
        List<OrganizationListInfo> dtoList = new ArrayList<>(poList.size());
        if (!poList.isEmpty()) {
            dtoList = poList.stream().map(OrganizationListInfo::new).collect(Collectors.toList());
        }
        return dtoList;
    }

    @Override
    public IPage<OrganizationListInfo> pageOrganization(OrganizationPageRequest request) {
        LambdaQueryWrapper<DtrdEntRdOrganization> queryWrapper = baseQueryWrapper();

        if (StrUtil.isNotBlank(request.getDistrict())) {
            String[] district = request.getDistrict().split(",");
            if (district.length == 3) {
                queryWrapper.eq(DtrdEntRdOrganization::getOrganizationAreaId, district[2]);
                queryWrapper.eq(DtrdEntRdOrganization::getOrganizationCityId, district[1]);
                queryWrapper.eq(DtrdEntRdOrganization::getOrganizationProvinceId, district[0]);
            } else if (district.length == 2) {
                queryWrapper.eq(DtrdEntRdOrganization::getOrganizationCityId, district[1]);
                queryWrapper.eq(DtrdEntRdOrganization::getOrganizationProvinceId, district[0]);
            } else if (district.length == 1) {
                queryWrapper.eq(DtrdEntRdOrganization::getOrganizationProvinceId, district[0]);
            }
        }

        IPage<DtrdEntRdOrganization> page = new Page<>(request.getPageNum(), request.getPageSize());
        page = this.page(page, queryWrapper);
        // 查询看着没问题  ，转换需要加省市区的响应逻辑
        return page.convert(item->conveter(item));
    }

    private OrganizationListInfo conveter(DtrdEntRdOrganization po){
        OrganizationListInfo item = new OrganizationListInfo(po);
        item.setOrganizationAddress(joinProvinceCityArea(po.getOrganizationProvinceId(),po.getOrganizationCityId(),po.getOrganizationAreaId())+po.getOrganizationAddress());
        return item;
    }

    @Override
    public OrganizationDetail getOrganization(Integer dataId, String orgCode) {
        LambdaQueryWrapper<DtrdEntRdOrganization> queryWrapper = baseQueryWrapper();
        if (dataId != null) {
            queryWrapper.eq(DtrdEntRdOrganization::getDataId, dataId);
        }
        if (StrUtil.isNotBlank(orgCode)) {
            queryWrapper.eq(DtrdEntRdOrganization::getOrganizationCode, orgCode);
        }
        DtrdEntRdOrganization dtrdEntRdOrganization = getOne(queryWrapper);
        return Optional.ofNullable(dtrdEntRdOrganization)
                        .map(po -> {
                            OrganizationDetail organizationDetail = new OrganizationDetail().parseFromPo(po);
//                            organizationDetail.setOrganizationAddress(joinProvinceCityArea(po.getOrganizationProvinceId(),po.getOrganizationCityId(),po.getOrganizationAreaId()));
                            return organizationDetail;
                        })
                        .orElse(null);
    }

    private String joinProvinceCityArea(Integer organizationProvinceId, Integer organizationCityId, Integer organizationAreaId) {
        StringJoiner joiner = new StringJoiner("");
        if (organizationProvinceId != null) {
            String province = districtInfoService.getDistrictNameByAreaId(organizationProvinceId);
            joiner.add(province);
        }
        if (organizationCityId != null) {
            String city = districtInfoService.getDistrictNameByAreaId(organizationCityId);
            joiner.add(city);
        }
        if (organizationAreaId != null) {
            String area = districtInfoService.getDistrictNameByAreaId(organizationAreaId);
            joiner.add(area);
        }
        return joiner.toString();
    }


    @Override
    public String getOrgName(String orgCode) {
        LambdaQueryWrapper<DtrdEntRdOrganization> queryWrapper = Wrappers.lambdaQuery(DtrdEntRdOrganization.class)
                .eq(DtrdEntRdOrganization::getOrganizationCode, orgCode);
        DtrdEntRdOrganization query = this.getOne(queryWrapper);
        return Optional.ofNullable(query).map(DtrdEntRdOrganization::getOrganizationName).orElse(null);
    }

    @Override
    public boolean saveOrUpdateOrganization(OrganizationDetail dto) {
        DtrdEntRdOrganization dtrdEntRdOrganization = new DtrdEntRdOrganization();
        if(dto.getDataId() == null){
            dtrdEntRdOrganization = dtrdEntRdOrganization.init();
            if (getOrgName(dto.getOrganizationCode()) != null) {
                return false;
            }
        }
        dtrdEntRdOrganization.parseFromDto(dto);
        return saveOrUpdate(dtrdEntRdOrganization);
    }

    @Override
    public boolean removeOrganization(Integer dataId) {
        return removeById(dataId);
    }

    private LambdaQueryWrapper<DtrdEntRdOrganization> baseQueryWrapper() {
        return Wrappers.lambdaQuery(DtrdEntRdOrganization.class)
                        .eq(DtrdEntRdOrganization::getIsDel, 0);
    }

    private LambdaUpdateWrapper<DtrdEntRdOrganization> baseUpdateWrapper() {
        return Wrappers.lambdaUpdate(DtrdEntRdOrganization.class)
                        .eq(DtrdEntRdOrganization::getIsDel, 0);
    }
}
